from typing import Optional

from fastapi import Query, Body, Request, Header, Depends
from fastapi_utils.cbv import cbv
from fastapi_utils.inferring_router import InferringRouter
from sqlalchemy.orm import Session

from server.app.cloud_ide.schema.ide.request.ide_create_request import IdeCreateRequest
from server.app.cloud_ide.schema.ide.request.ide_update_request import IdeUpdateRequest
from server.app.cloud_ide.service.ide_service import IdeService
from server.framework.core.http_schemas import CommonResponseSchema, TableResponseSchema
from server.framework.core.injects import get_db
from server.framework.core.settings import settings

ide_api = InferringRouter()


@cbv(ide_api)
class IdeApi:
    ide_service = IdeService()
    db: Session = Depends(get_db)

    @ide_api.get("/get_entity", name='获取ide实体')
    async def get_entity(self, id: str = Query(None, description='开发环境id')):
        entity = self.ide_service.get_ide_by_id(self.db, id)
        return entity

    @ide_api.get("/list", response_model=TableResponseSchema, name='获取IDE列表')
    async def list(
            self,
            request: Request,
            group: Optional[str] = Header(None),
            name: Optional[str] = Query(None, description='过滤条件:ide名称'),
            current: Optional[int] = Query(1, description='当前页数'),
            page_size: Optional[int] = Query(10, description='每页记录的数量', alias='pageSize')) -> TableResponseSchema:
        """
        获取IDE列表
        :return:
        """
        if request.state.is_admin:
            items, total = self.ide_service.get_ide_list(self.db, request.state.user_id, group, name, page_size,
                                                         current,
                                                         filter_by_user=False)
        else:
            items, total = self.ide_service.get_ide_list(self.db, request.state.user_id, group, name, page_size,
                                                         current,
                                                         filter_by_user=True)
        return TableResponseSchema(data=items, total=total, page=page_size, success=True)

    @ide_api.post("/create", response_model=CommonResponseSchema, name='创建IDE')
    async def create(self, request: Request,
                     data: IdeCreateRequest = Body(None, description='IDE创建实体'),
                     group: Optional[str] = Header(None)) -> CommonResponseSchema:
        """
        创建IDE
        :return:
        """
        data.tenant_id = group
        rs = self.ide_service.create_ide(self.db, request.state.user_name, request.state.user_id,
                                         data)
        if rs:
            return CommonResponseSchema(data={}, message=f'创建成功', success=True)
        else:
            return CommonResponseSchema(data={}, message=f'创建失败', success=False)

    @ide_api.get("/delete", response_model=CommonResponseSchema, name='删除IDE')
    async def delete(self, ids: str = Query(None, description='镜像id，多条记录以逗号分割'),
                     group: Optional[str] = Header(None)) -> CommonResponseSchema:
        rs = self.ide_service.delete_ide(self.db, ids.split(','), group)
        if rs:
            return CommonResponseSchema(data={}, message=f'删除成功', success=True)
        else:
            return CommonResponseSchema(data={}, message=f'删除失败', success=False)

    @ide_api.post("/edit", response_model=CommonResponseSchema, name='编辑IDE')
    async def edit(self, data: IdeUpdateRequest = Body(None, description='编辑IDE实体'),
                   group: Optional[str] = Header(None)) -> CommonResponseSchema:
        data.tenant_id = group
        rs = self.ide_service.update_ide(self.db, data)
        if rs:
            return CommonResponseSchema(data={}, message=f'编辑成功', success=True)
        else:
            return CommonResponseSchema(data={}, message=f'编辑失败', success=False)

    @ide_api.get("/get_ide_url", name='获取IDE地址', response_model=CommonResponseSchema)
    async def get_ide_url(self, id: str = Query(None, description='开发环境id')):
        ide = self.ide_service.get_ide_by_id(self.db, id)
        return CommonResponseSchema(data={'url': f'http://{ide.id}.{settings.ide_domain}'}, message=f'')

    @ide_api.get("/start", name='启动IDE', response_model=CommonResponseSchema)
    async def start(self, id: str = Query(None, description='开发环境id'),
                    group: Optional[str] = Header(None)):
        """
        启动IDE
        :return:
        """

        rs = self.ide_service.start_ide(self.db, id, group)
        if rs:
            return CommonResponseSchema(data={}, message=f'启动成功', success=True)
        else:
            return CommonResponseSchema(data={}, message=f'启动失败', success=False)

    @ide_api.get("/stop", name='暂停IDE', response_model=CommonResponseSchema)
    async def stop(self, id: str = Query(None, description='开发环境id'),
                   group: Optional[str] = Header(None)):
        """
        停止IDE
        :return:
        """
        rs = self.ide_service.stop_ide(self.db, id, group)
        if rs:
            return CommonResponseSchema(data={}, message=f'停止成功', success=True)
        else:
            return CommonResponseSchema(data={}, message=f'停止失败', success=False)
